//
//  CapacitySearchViewController.m
//  厨房助手
//
//  Created by 0.0 on 15-4-13.
//  Copyright (c) 2015年 dingjun. All rights reserved.
//

#import "CapacitySearchViewController.h"
#import "DetailController.h"
#import "SearchResultViewController.h"
#import "ResultView.h"
#import "VegetableButton.h"


@interface CapacitySearchViewController ()
{
    UIView *_resultView;
    UIButton *_resultButton;
    NSInteger _numItem;
    UIScrollView *_smallScroll; // 上下滚动条
    UIScrollView *_scroll; // 左右滚动条
    
   
    
}

@property (nonatomic, retain) NSMutableArray *allArray; // 存放所有类别的数组
@property (nonatomic, retain) NSArray *nameArray; // 存放所有类别名字的数组
@property (nonatomic, retain) NSMutableArray *resultArray; // 存放用户选择的菜的tag值
@property (nonatomic, retain) UILabel *noticeLabel; // 创建resultview上的提示信息

@end

@implementation CapacitySearchViewController

- (void)dealloc
{
    [_allArray release];
    [_nameArray release];
    [_resultArray release];
    [_noticeLabel release];
   
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.allArray = [NSMutableArray array];
        self.nameArray = @[@"蔬菜-茎叶类", @"蔬菜-块根类", @"蔬菜-瓜果类", @"蔬菜-豆类", @"菌菇类", @"畜肉类", @"禽肉类", @"蛋类", @"水产类", @"水果类", @"干果类", @"粮豆米面类", @"烘培类", @"常见中药材", @"其他"];
        self.resultArray = [NSMutableArray array];
        
        
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getNavigationBar];
    [self creatBackGround];
    [self getThingFromJson];
    [self createResultView];
    // 创建resultView里的提示Label, 选菜之后就隐藏
    [self createNoticeLabel];
    [self createVegetabelCollectionView];
}

- (void)creatBackGround
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [imageView setImage:[UIImage imageNamed:@"thirdBarBackground.jpg"]];
    [self.view addSubview:imageView];
    [imageView release];
    
}

#pragma mark - 创建搜索提示view里地提示信息
- (void)createNoticeLabel
{
    self.noticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, (_resultView.frame.size.height / 2) - 20, _resultView.frame.size.width, 40)];
    _noticeLabel.font = [UIFont systemFontOfSize:15.0f];
    _noticeLabel.text = @"看看冰箱里还有什么菜, 在下面类别选择一下吧.";
    _noticeLabel.textColor = [UIColor whiteColor];
    [_resultView addSubview:_noticeLabel];
    [_noticeLabel release];
    
}

- (void)getThingFromJson
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![defaults objectForKey:@"login"]) {
        [defaults setObject:@"YES" forKey:@"login"];
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"看看冰箱里还有什么菜" message:@"选择底下菜搜索可以做什么" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [view show];
        [view release];
    }
    NSString *path = [[NSBundle mainBundle] pathForResource:@"CapSearch" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSError *error = nil;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    for (NSArray *brray in array) {
        [self.allArray addObject:brray];
    }

    
   
}

#pragma mark - 配置navigationBar
- (void)getNavigationBar
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"智能搜索";
    [self.view setBackgroundColor:[UIColor clearColor]];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
}


#pragma mark - 搭建结果界面
- (void)createResultView
{
    _resultView = [[UIView alloc] initWithFrame:CGRectMake(20, 20 + 64, self.view.frame.size.width - 40, self.view.frame.size.height / 5 - 20)];
    _resultView.layer.cornerRadius = 10.0;
    _resultView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_resultView];
    _resultView.layer.borderWidth = 1.0;
    // 设置颜色空间为rgb，用于生成ColorRef
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    // 新建一个红色的ColorRef，用于设置边框（四个数字分别是 r, g, b, alpha）
    CGColorRef borderColorRef = CGColorCreate(colorSpace,(CGFloat[]){255, 255, 255, 1});
    // 设置边框颜色
    _resultView.layer.borderColor = borderColorRef;
    
    _resultButton = [[UIButton alloc] initWithFrame:CGRectMake(_resultView.frame.origin.x + _resultView.frame.size.width - _resultView.frame.size.width / 4, _resultView.frame.origin.y + _resultView.frame.size.height + 20, _resultView.frame.size.width / 4, 40)];
    _resultButton.layer.cornerRadius = 8.0f;
    [_resultButton addTarget:self action:@selector(goResultClick) forControlEvents:UIControlEventTouchUpInside];
    [_resultButton setTitle:@"搜 索" forState:UIControlStateNormal];
    _resultButton.layer.borderWidth = 1.0f;
    [_resultButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_resultButton addTarget:self action:@selector(buttonDown) forControlEvents:UIControlEventTouchDown];
    [_resultButton addTarget:self action:@selector(buttonUp) forControlEvents:UIControlEventTouchUpInside];
    [_resultButton addTarget:self action:@selector(buttonUp) forControlEvents:UIControlEventTouchUpOutside];
    [self.view addSubview:_resultButton];
}

- (void)buttonDown
{
    _resultButton.backgroundColor = [UIColor grayColor];
}

- (void)buttonUp
{
    _resultButton.backgroundColor = [UIColor clearColor];
}

#pragma mark - 搭建菜品界面
- (void)createVegetabelCollectionView
{
    // 左右滑动的scrollView
    _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(10, self.view.frame.origin.y + 20 + 44 + 20 + _resultView.frame.size.height + 20 + _resultButton.frame.size.height + 30, self.view.frame.size.width, self.view.frame.size.height - (self.view.frame.origin.y + 20 + 44 + 20 + _resultView.frame.size.height + 20 + _resultButton.frame.size.height))];
    
    // 创建上下滑动scrollview
    [self createSmallCollectionView];
    [self.view addSubview:_scroll];
    
    _scroll.contentSize = CGSizeMake(15 * 170, _scroll.frame.size.height);
    
}

#pragma mark - 创建菜的按钮
- (void)createSmallCollectionView
{
    for (int i = 0; i < [self.allArray count]; i++) {
        // 菜的类的label
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(_scroll.bounds.origin.x + i * 170, _scroll.bounds.origin.y, 150, 30)];
        [label setTextColor:[UIColor whiteColor]];
        label.textAlignment = NSTextAlignmentCenter;
        NSString *str = [self.nameArray objectAtIndex:i];
        label.text = str;
        [_scroll addSubview:label];
        
        
        _smallScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(label.frame.origin.x, label.frame.origin.y + label.frame.size.height, 150, self.view.frame.size.height - 20 - 44 - 20 - _resultView.frame.size.height - 20 - _resultButton.frame.size.height - 30 - 44)];
        _smallScroll.backgroundColor = [UIColor whiteColor];
        _smallScroll.layer.cornerRadius = 10.0;
        
        CGFloat myX = 5;
        CGFloat myY = 10;
        NSInteger num = [[self.allArray objectAtIndex:i] count] / 2;
        // 创建菜品按钮
        for (int j = 0; j < num; j++) {
            
            VegetableButton *button = [[VegetableButton alloc] initWithFrame:CGRectMake(myX, myY, 65, 65)];
//            button.backgroundColor = [UIColor clearColor];
            
            [button setBackgroundImage:[UIImage imageNamed:@"thirdBarBackground.jpg"] forState:UIControlStateNormal];
            button.layer.masksToBounds = YES;
            button.layer.borderWidth = 1.2f;
            button.layer.cornerRadius = 8.0f;
//            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.VBNameLabel.font = [UIFont systemFontOfSize:13.0f];
//            button.titleLabel.font = [UIFont systemFontOfSize:13.0f];
            button.VBNameLabel.textAlignment = NSTextAlignmentCenter;
//            button.titleLabel.textAlignment = NSTextAlignmentLeft;
            NSString *str = [[self.allArray objectAtIndex:i] objectAtIndex:(j * 2)];
//            [button setTitle:str forState:UIControlStateNormal];
            [button.VBNameLabel setText:str];
            button.VBNameLabel.textColor = [UIColor whiteColor];
            NSString *numb = [[self.allArray objectAtIndex:i] objectAtIndex:(j * 2) + 1];
            button.tag = numb.integerValue;
            [button addTarget:self action:@selector(buttonClick2:) forControlEvents:UIControlEventTouchUpInside];
            if (j % 2 != 0) {
                myX = 5;
                myY += 65 + 10;
            }
            else {
                myX += 65 + 10;
                
            }
            
            [_smallScroll addSubview:button];
            _smallScroll.contentSize = CGSizeMake(label.frame.size.width, (num + 1) / 2 * (65 + 10) + 44);
            [_scroll addSubview:_smallScroll];
        }
      
}
}

- (void)goResultClick
{
    if (0 != [self.resultArray count]) {
        SearchResultViewController *searchView = [[SearchResultViewController alloc] init];
        NSMutableArray *tagArray = [NSMutableArray array];
        for (UIButton *button in self.resultArray) {
            [tagArray addObject:[NSString stringWithFormat:@"%ld", button.tag]];
        }
        searchView.array = tagArray;
        searchView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:searchView animated:YES];
        [searchView release];
    }
}

// 用户选择菜品
- (void)buttonClick2:(VegetableButton *)button
{
    if (self.noticeLabel != nil) {
    [_noticeLabel removeFromSuperview];
    }

    // 检查重复 有重复返回NO, 没有重复返回yes
    BOOL isSame = [self checkSame:button];
    
    if (isSame) {
        if ([self.resultArray count] < 6) {
            [self.resultArray addObject:button];
            [self drawButtonInResult];
        }
        else {
            UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"最多只能选择6种菜品" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [view show];
            [view release];
        }
    }
}

- (void)drawButtonInResult
{
    CGFloat offX = 10;
    CGFloat offY = 10;
    for (UIView *view in _resultView.subviews) {
        [view removeFromSuperview];
    }
    
    for (int i = 0; i < [self.resultArray count]; i++) {
        ResultView *view = [[ResultView alloc] initWithFrame:CGRectMake(offX, offY, (_resultView.frame.size.width - 40) / 3, 50)];
        VegetableButton *button = [self.resultArray objectAtIndex:i];
        [view.nameLabel setBackgroundColor:[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1.0]];
        [view.nameLabel setText:button.VBNameLabel.text];
//        [view.nameLabel setTextColor:[UIColor whiteColor]];
        view.cancelButton.tag = button.tag;
        [view.cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_resultView addSubview:view];
        if (i == 2) {
            offX = 10;
            offY += 30 + 20;
        }
        else {
            offX += (_resultView.frame.size.width - 40) / 3 + 10;
        }
    }
}


- (BOOL)checkSame:(UIButton *)button
{
    for (UIButton *button2 in self.resultArray) {
        if (button.tag == button2.tag) {
            return NO;
        }
    }
    return YES;
}

#pragma mark - 删除结果view里的菜品
- (void)cancelButtonClick:(UIButton *)button
{
//    NSArray *array = [NSArray arrayWithArray:self.resultArray];
    for (UIButton *button2 in self.resultArray) {
        if (button.tag == button2.tag) {
            [self.resultArray removeObject:button2];
            [self drawButtonInResult];
            return;
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
